#include<iostream>
#include<unistd.h>
#include<cstring>
using namespace std;
void wrprc(int fd)
{
    string s = "syx 666";
    int ct = 0;
    int id = getpid();
    while (1)
    {
        string message = to_string(id) + ":" + s + to_string(ct++);
        write(fd, message.c_str(), message.size());
        cout << message << endl;
        sleep(1);
    }
}
void rdprc(int fd)
{
    int id = getpid();
    char buffer[512];
    while (1)
    {
        ssize_t n = read(fd, buffer, 511);
        if(n>0)
        {
            buffer[511] = '\0';
            cout << id << ' ' << n << ":" << buffer << endl;
            sleep(1);
        }
        if(n==0)
        {
            return;
        }
    }
}
int main()
{
    int pipefd[2];
    int n = pipe(pipefd);
    if(n!=0)
    {
        cerr << "error:" << errno << "errorstring" << strerror(errno) << endl;
        return 1;
    }
    //0 read 1 write
    cout << pipefd[0] << ':' << pipefd[1] << endl;
    pid_t id = fork();
    if(id==0)
    {
        close(pipefd[0]);
        wrprc(pipefd[1]);
        close(pipefd[1]);
    }
    else{
        close(pipefd[1]);
        rdprc(pipefd[0]);
        close(pipefd[0]);
    }
    return 0;
}